package utils

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var DB *gorm.DB

func InitConfig() {
	fmt.Println("init config began")
	beganTime := time.Now().Unix()
	viper.SetConfigName("application")
	viper.AddConfigPath("./config")
	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	overTime := time.Now().Unix()
	useTime := overTime - beganTime
	fmt.Printf("init main config success, use time %d \n", useTime)
}

func InitMySQL() {
	fmt.Println("init mysql began")
	beganTime := time.Now().Unix()
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			Colorful:      true,
			LogLevel:      logger.Info,
		},
	)
	dsn := fmt.Sprintf(viper.GetString("mysql.username") + ":" + viper.GetString("mysql.password") + "@" + viper.GetString("mysql.protocol") + "(" + viper.GetString("mysql.address") + ":" + viper.GetString("mysql.port") + ")/" + viper.GetString("mysql.dbname") + "?" + viper.GetString("mysql.other"))
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		fmt.Println("init mysql fail", err)
		return
	} else {
		overTime := time.Now().Unix()
		useTime := overTime - beganTime
		fmt.Printf("init mysql success,use time %d \n", useTime)
	}
}
